# -*- coding: utf-8 -*-
# @Time    : 2021/4/13 18:59
# @Author  : mokez
# @Email   : 1569089678@qq.com
# @File    : ips.py
# @Software: PyCharm
# ip存储与读取文件统计ip频率 (京东二面题)
# • 生成一个大文件ips.txt,要求120000行，每行随即为172.25.254.0/24段的ip;
# • 读取ips.txt文件统计这个文件中ip出现频率前10的ip

import random


def create_file():
    with open("ips.txt", mode="w", encoding="utf-8") as fp1:
        for i in range(120000):
            line = f"172.25.254.{random.randint(0, 255)}\n"
            fp1.write(line)


def read_file():
    with open("ips.txt", mode="r", encoding="utf-8") as fp2:
        dc = {}
        for ip in fp2:
            if ip in dc:
                dc[ip] += 1
            else:
                dc[ip] = 1
        # print(dc)
        top10 = sorted(dc.items(), key=lambda d: d[1], reverse=True)[:10]
        return top10


create_file()
result = read_file()
print(result)
